package com.gouying.web.exception;

import com.alibaba.fastjson.JSON;
import com.gouying.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@ControllerAdvice
@RestControllerAdvice("com.gouying.web.controller")
public class ProductAdvice {


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        Map<String, String> errorMap = new HashMap<>(16);
        fieldErrors.forEach(fieldError -> {
            final String field = fieldError.getField();
            final String defaultMessage = fieldError.getDefaultMessage();
            errorMap.put(field, defaultMessage);

        });
        return R.error(500, JSON.toJSONString(errorMap));
    }


    /**
     * 其他所有未知的异常
     *
     * @param throwable
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        log.error("错误：", throwable);
        return R.error(500, "未知错误");
    }

    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler({HttpMediaTypeNotSupportedException.class})
    public R handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
        log.error("[MyGlobalExceptionHandler.handleHttpMediaTypeNotSupportedException] 不支持当前媒体类型: {}", e);
        return R.error(500,"不支持当前媒体类型");
    }

    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public R handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("[MyGlobalExceptionHandler.handleHttpRequestMethodNotSupportedException] 不支持当前请求方法: {}", e);
        return R.error(500,"不支持当前请求方法");
    }

}
